import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';
import 'package:amap_map_fluttify/amap_map_fluttify.dart';

Effect<StoreDetailViewState> buildEffect() {
  return combineEffects(<Object, Effect<StoreDetailViewState>>{
    StoreDetailViewAction.onCall: _onCall,
    StoreDetailViewAction.addMarker: _addMarker,
    StoreDetailViewAction.onIndexChange: _onIndexChange,
    Lifecycle.initState: _initState,
  });
}

void _onIndexChange(Action action, Context<StoreDetailViewState> ctx) async {
  StoreDetailModel model = ctx.state.models[action.payload];
  await ctx.state.controller.setCenterCoordinate(LatLng(model.lat, model.lng),
      animated: true, zoomLevel: 15);
}

void _initState(Action action, Context<StoreDetailViewState> ctx) {
  List<StoreDetailModel> list = [
    // StoreDetailModel(
    //   storeName: '昆仑燃气总公司',
    //   storeAddress: '睢阳区归德路与商永路交叉口路西',
    //   phone: '17550290811',
    //   storeTime: '08:00-12:00、14:00-18:00',
    //   lat: 34.34600976818112,
    //   lng: 115.66124254616386,
    // ),
    // StoreDetailModel(
    //   storeName: '昆仑燃气郭村营业厅',
    //   storeAddress: '睢阳区平安大道与024县道交叉口南约100米',
    //   phone: '15137059331',
    //   storeTime: '08:00-12:00、14:00-18:00',
    //   lat: 34.35267678219134,
    //   lng: 115.47149976261989,
    // ),
    // StoreDetailModel(
    //   storeName: '昆仑燃气坞墙营业厅',
    //   storeAddress: '睢阳区京澳线坞墙二中西北侧约110米',
    //   phone: '13223003567',
    //   storeTime: '08:00-12:00、14:00-18:00',
    //   lat: 34.15395475991673,
    //   lng: 115.69787018863701,
    // ),
    // StoreDetailModel(
    //   storeName: '昆仑燃气平台营业厅',
    //   storeAddress: '梁园区商都大道南段220号',
    //   phone: '18738052331',
    //   storeTime: '08:00-12:00、14:00-18:00',
    //   lat: 34.39808183453914,
    //   lng: 115.72411772168158,
    // ),
  ];
  ctx.dispatch(StoreDetailViewActionCreator.onGetData({'model': list}));
}

void _onCall(Action action, Context<StoreDetailViewState> ctx) async {
  CommonUtils.callPhone(
    action.payload,
    ctx.context,
  );
}

void _addMarker(Action action, Context<StoreDetailViewState> ctx) async {
  AmapController controller = action.payload;
  if (controller != null) {
    List<MarkerOption> markers = ctx.state.models
        .map<MarkerOption>((e) =>
            MarkerOption(latLng: LatLng(e.lat, e.lng), title: e.storeName))
        .toList();

    await controller.setCenterCoordinate(markers.first.latLng,
        animated: false, zoomLevel: 15);
    await controller.addMarkers(markers);
    await controller.setInfoWindowClickListener((marker) async {
      LatLng location = await marker.location;
      await CommonUtils.showLocationNavigation(
          location.latitude, location.longitude, ctx.context);
    });
    ctx.state.controller = controller;
    ctx.dispatch(StoreDetailViewActionCreator.onAction());
  }
}
